package cn.cycleif.admin.service;

import cn.cycleif.admin.pojo.dto.AdminReportRejectDTO;
import cn.cycleif.admin.pojo.dto.AdminReportResolveDTO;
import cn.cycleif.admin.pojo.vo.SysReportVO;
import cn.cycleif.app.mapper.ReportMapper;
import cn.cycleif.app.mapper.UserMapper;
import cn.cycleif.app.service.NotificationService;
import cn.cycleif.app.service.UserService;
import cn.cycleif.entity.Notification;
import cn.cycleif.entity.Report;
import cn.cycleif.entity.User;
import cn.cycleif.enums.*;
import cn.cycleif.util.PageUtil;
import cn.cycleif.util.R;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;

/**
 * @Date: 25/2/12-15:48
 * @Desc:
 */
@Service
@RequiredArgsConstructor
public class AdminReportService extends ServiceImpl<ReportMapper, Report> {

  private final ReportMapper        reportMapper;
  private final UserService         userService;
  private final UserMapper          userMapper;
  private final NotificationService notificationService;

  public R<Object> getPage() {
    Page<Report>               page    = new Page<>(PageUtil.getPageNo(), PageUtil.getPageSize());
    LambdaQueryWrapper<Report> wrapper = new LambdaQueryWrapper<>();
    wrapper.eq(Report::getStatus, CommonStatusEnum.ACTIVE.getValue());
    wrapper.orderByDesc(Report::getCreateAt);

    Page<Report> reports = reportMapper.selectPage(page, wrapper);

    Page<SysReportVO> voPage = new Page<>();
    voPage.setCurrent(reports.getCurrent());
    voPage.setSize(reports.getSize());
    voPage.setTotal(reports.getTotal());
    voPage.setPages(reports.getPages());

    // 添加其他信息
    List<Report>      records    = reports.getRecords();
    List<SysReportVO> sysUserVOS = records.stream().map(this::appendExtraInfo).toList();
    voPage.setRecords(sysUserVOS);
    return R.success(voPage);
  }

  private SysReportVO appendExtraInfo(Report report) {
    SysReportVO vo = BeanUtil.copyProperties(report, SysReportVO.class);

    HashMap<String, Object> userInfo = userService.getUserSimpleInfo(report.getUserId(), null);
    HashMap<String, Object> reportedUserInfo =
        userService.getUserSimpleInfo(report.getReportedUserId(), null);
    vo.setUserInfo(userInfo);
    vo.setReportedUserInfo(reportedUserInfo);
    return vo;
  }

  public R<Long> getCount() {
    LambdaQueryWrapper<Report> wrapper = new LambdaQueryWrapper<>();
    wrapper.eq(Report::getStatus, CommonStatusEnum.ACTIVE.getValue());
    return R.success(reportMapper.selectCount(wrapper));
  }

  @Transactional(rollbackFor = Exception.class)
  public R<Object> reject(AdminReportRejectDTO dto) {
    int    userId = StpUtil.getLoginIdAsInt();
    Report report = reportMapper.selectById(dto.getReportId());
    if (report == null) {
      return R.error(ResultCodeEnum.ERROR_NOT_EXIST);
    }
    report.setStatus(CommonStatusEnum.DISABLE);
    report.setResolveUserId(userId);
    reportMapper.updateById(report);

    Notification notification = new Notification();
    notification.setActionType(ActionTypeEnum.REJECTED);
    notification.setType(InboxTypeEnum.OTHER);
    notification.setObjectId(report.getObjectId());
    notification.setObjectType(report.getObjectType());
    notification.setIsRead(0);
    notification.setStatus(CommonStatusEnum.ACTIVE);
    notification.setUserId(report.getUserId());
    notification.setContent(
        "您的举报已被驳回，举报编号：**" + report.getId() + "**" +
            "  \n" +
            "举报类型：" + report.getObjectType().getDesc() +
            "  \n" +
            "举报内容：" + report.getFlaggedContent() +
            "  \n" +
            "驳回原因: **" + dto.getReason() +
            (StringUtils.isEmpty(dto.getExtra())
                ? "**"
                : ", " + dto.getExtra() + "**")
    );
    notificationService.addNotification(notification);
    return R.success();
  }

  @Transactional(rollbackFor = Exception.class)
  public R<Object> resolve(AdminReportResolveDTO dto) {
    int    userId = StpUtil.getLoginIdAsInt();
    Report report = reportMapper.selectById(dto.getReportId());
    if (report == null) {
      return R.error(ResultCodeEnum.ERROR_NOT_EXIST);
    }
    report.setResolveUserId(userId);
    report.setStatus(CommonStatusEnum.DISABLE);
    reportMapper.updateById(report);

    if (dto.getUserType() == 0) {
      // 警告用户
      Notification notification = new Notification();
      notification.setActionType(ActionTypeEnum.WARN);
      notification.setType(InboxTypeEnum.OTHER);
      notification.setObjectId(report.getObjectId());
      notification.setObjectType(report.getObjectType());
      notification.setIsRead(0);
      notification.setStatus(CommonStatusEnum.ACTIVE);
      notification.setUserId(report.getReportedUserId());
      notification.setContent(
          "您已违规，举报编号：**" + report.getId() + "**" +
              "  \n" +
              "违规类型：" + report.getObjectType().getDesc() +
              "  \n" +
              "违规内容：" + report.getFlaggedContent() +
              "  \n" +
              "处理信息：**" + dto.getInfoToUser() + "**" +
              "  \n> " + report.getContent()
      );
      notificationService.addNotification(notification);
    } else if (dto.getUserType() == 2) {

      LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
      wrapper.eq(User::getId, report.getReportedUserId());
      User user = userMapper.selectOne(wrapper);
      user.setStatus(UserStatusEnum.DISABLE);
      user.setSuspendAt(LocalDateTime.now());
      LocalDateTime userUntil = dto.getUserUntil();
      if (userUntil != null) user.setSuspendAt(userUntil);
      userMapper.updateById(user);   // 封禁用户
    }

    Notification notification = new Notification();
    notification.setActionType(ActionTypeEnum.ACCEPTED);
    notification.setType(InboxTypeEnum.OTHER);
    notification.setObjectId(report.getObjectId());
    notification.setObjectType(report.getObjectType());
    notification.setIsRead(0);
    notification.setStatus(CommonStatusEnum.ACTIVE);
    notification.setUserId(report.getUserId());
    notification.setContent(
        "您的举报已处理，举报编号：**" + report.getId() + "**" +
            "  \n" +
            "举报类型：" + report.getObjectType().getDesc() +
            "  \n" +
            "举报内容：" + report.getFlaggedContent() +
            "  \n> " + report.getContent()
    );
    notificationService.addNotification(notification);
    return R.success();
  }
}
